package webmailpkg;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GestioneMail
 */
@WebServlet("/GestioneMail")
public class GestioneMail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GestioneMail() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String riscontro;
		
		response.setContentType("text/html");
		String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n";
		String title = "Rapporto invio email\n";
		
		//Input Username e Password
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username);
		PrintWriter out = response.getWriter();
		riscontro =  sendMail(username, password);
		out.println(docType +
					"<HTML>\n" +
					"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"+
					"<BODY BGCOLOR=\"#FDF5E6\">\n" +
					"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
					"<TABLE>\n" +
					"<TR>\n" +
					"<TH>"+ riscontro +
					"<TR> ARRIVEDERCI </TR>" +
					"</TABLE>");	
	}

	
	protected String sendMail(String username, String password) {
		String output = "Message sent";
		String host = "mail.eng.it";
		int port = 25;

 
	    Properties props = new Properties();
	    props.put("mail.smtp.host", "mail.eng.it");
	    props.put("mail.smtp.port", "25");
	    props.put("mail.from", "luca.boriosi@eng.it");
	    Session session = Session.getInstance(props, null);

	    try {
	        MimeMessage msg = new MimeMessage(session);
	        msg.setFrom();
	        msg.setRecipients(Message.RecipientType.TO,
	                          "you@example.com");
	        msg.setSubject("JavaMail hello world example");
	        msg.setText("Hello, world!\n");
	        Transport.send(msg);
	    } catch (MessagingException mex) {
	        System.out.println("send failed, exception: " + mex);
	        output = "send failed, exception: " + mex;
	    }
	    return output;
	}
}

